package com.ztmg.water.service.bills.impl;

import com.alibaba.fastjson.JSON;
import com.ztmg.common.constant.CommonConstants;
import com.ztmg.common.util.DateUtil;
import com.ztmg.common.util.RandomUtil;
import com.ztmg.common.util.StringUtil;
import com.ztmg.water.dto.base.DeliveryManDTO;
import com.ztmg.water.mapper.base.DeliveryManMapper;
import com.ztmg.water.mapper.bills.OutPutBillsMapper;
import com.ztmg.water.mapper.bills.WaterStockMapper;
import com.ztmg.water.mapper.order.OrderWaterMapper;
import com.ztmg.water.model.base.DeliveryMan;
import com.ztmg.water.model.base.DeliveryManExample;
import com.ztmg.water.model.base.DepositRecord;
import com.ztmg.water.model.bills.*;
import com.ztmg.water.model.order.OrderWater;
import com.ztmg.water.vo.bills.OutPutBillsVO;
import com.ztmg.water.dto.bills.OutPutBillsDTO;
import com.ztmg.water.dto.bills.OutPutBillsPageDTO;
import com.ztmg.common.util.resultUtils.JsonResult;
import javax.annotation.Resource;

import com.ztmg.water.vo.order.OrderWaterVO;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ztmg.common.constant.ErrorConst;
import org.springframework.beans.BeanUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.ztmg.water.service.bills.OutPutBillsService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OutPutBillsServiceImpl implements OutPutBillsService{

    @Resource
    private OutPutBillsMapper outPutBillsMapper;
    @Resource
    private OrderWaterMapper  orderWaterMapper;
    @Resource
    private DeliveryManMapper deliveryManMapper;
    @Resource
    private WaterStockMapper waterStockMapper;
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public JsonResult create(OutPutBillsDTO dto) {
        if(null != dto){
            OutPutBills bean = new OutPutBills();
            BeanUtils.copyProperties(dto,bean);
            String[] orderArray = bean.getOrderIds().split(",");
            if(!orderArray[0].equals("") && orderArray.length>0)
            {
                StringBuilder orderIds = new StringBuilder();
                orderIds.append("(");
                for (int i=0;i<orderArray.length;i++)
                {

                    orderIds.append("\"");
                    orderIds.append(orderArray[i]);
                    orderIds.append("\"");
                    orderIds.append(",");
                }
                orderIds.delete(orderIds.length()-1,orderIds.length());
                orderIds.append(")");
                /**批量修改订单状态**/
                Map<String,String> updateStatusParams = new HashMap<>(2);
                updateStatusParams.put("orderId",orderIds.toString());
                updateStatusParams.put("status",String.valueOf(CommonConstants.WATER_ORDER_STATUS_3));
                orderWaterMapper.updateOrderStatusByOrderId(updateStatusParams);

                //记录当前订单给学生配送水时需要配送的空桶数
                orderWaterMapper.updateStatusAndSendBucketNumByOrderId(orderIds.toString());


                //统计当前选中的配送订单水的总数和回收桶的数量
                OutPutBillsDTO   params_bill = new    OutPutBillsDTO();
                params_bill.setOrderIds(orderIds.toString());
                Map<String,Object> resultMap = orderWaterMapper.selectCountWaterNumsByOrderId(params_bill);


                dto.setOrderIds(orderIds.toString());

                bean.setWaterNums(Integer.parseInt(resultMap.get("waterNumSum").toString()));
                bean.setRecycleBucketSum(Integer.parseInt(resultMap.get("recycleNumSum").toString()));
                bean.setBillSn(RandomUtil.getOrderIdByTime());
                bean.setOrderNums(orderArray.length);
                //获取配送人员信息
                DeliveryManDTO deliveryManDTO = new DeliveryManDTO();
                deliveryManDTO.setId(bean.getDeliveryId());
                DeliveryManExample example = new DeliveryManExample();
                DeliveryManExample.Criteria criteria =  example.createCriteria();
                criteria.andIdEqualTo(bean.getDeliveryId());
                List<DeliveryMan> deliveryManList = deliveryManMapper.selectByExample(example);
                bean.setDeliveryName(deliveryManList.get(0).getDeliveryName());
                bean.setDeliveryTel(deliveryManList.get(0).getDeliveryTel());
                bean.setCreateTime(new Date());
                bean.setModifyTime(new Date());
                //后续完善
                bean.setCreater("");
                bean.setStatus(1);
                bean.setAuditRemark("");
                bean.setAuditStatus(1);
                bean.setRemark("");
                outPutBillsMapper.insert(bean);


            }

            return JsonResult.success();
        }else {
            return JsonResult.fail(ErrorConst.SYSTEM_PARM_ERROR,ErrorConst.SYSTEM_PARM_ERROR_MSG);
        }
    }


    @Override
    public JsonResult update(OutPutBillsDTO dto) {
        if(null != dto && null != dto.getId()){
            OutPutBills bean = new OutPutBills();
            BeanUtils.copyProperties(dto,bean);
            bean.setModifyTime(new Date());
            //后续完善
            bean.setModifier("");
            outPutBillsMapper.updateByPrimaryKeySelective(bean);
            return JsonResult.success();
        }else {
            return JsonResult.fail(ErrorConst.SYSTEM_PARM_ERROR,ErrorConst.SYSTEM_PARM_ERROR_MSG);
        }
    }

    @Override
    public JsonResult<Map<String,Object>> handleCollectDate(OutPutBillsDTO dto) {
        Map<String,Object> collectMap = JSON.parseObject(dto.getCollectData());
        Map<String,Object> resultMap = new HashMap();
        StringBuilder errorMessage = new StringBuilder();
        StringBuilder orderIdsParams = new StringBuilder();
        OutPutBillsExample example = new OutPutBillsExample();
        OutPutBillsExample.Criteria criteria =  example.createCriteria();
        criteria.andIdEqualTo(dto.getId());
        /***
         * 修改配送单对应的订单状态
         */
        List<OutPutBills> sysUserList = outPutBillsMapper.selectByExample(example);
        String orderIds =  sysUserList.get(0).getOrderIds();
        orderIdsParams.append("(");
        if(null!=orderIds && !orderIds.equals(""))
        {
            String[] idArray = orderIds.split(",");
            for (int i=0;i<idArray.length;i++)
            {
                orderIdsParams.append("\"");
                orderIdsParams.append(idArray[i]);
                orderIdsParams.append("\"");
                orderIdsParams.append(",");
            }
            orderIdsParams.delete(orderIdsParams.length()-1,orderIdsParams.length());
        }
        orderIdsParams.append(")");
        //校验宿舍所对应的水数量是否正确
        Map<String,Object> params =  new HashMap<>();
        params.put("idsArray",orderIdsParams.toString());
        boolean flag = true;
        params.put("status",CommonConstants.WATER_ORDER_STATUS_3);
        List<OrderWaterVO> orderDetailList = orderWaterMapper.selectOrderDetailByOrderId(params);
        if(orderDetailList!=null && orderDetailList.size()>0)
        {
            for (OrderWaterVO orderObj:orderDetailList)
            {
                  if(null == collectMap.get(Base64.encodeBase64String(orderObj.getRoomSn().getBytes()))
                         || !collectMap.get(Base64.encodeBase64String(orderObj.getRoomSn().getBytes())).equals(String.valueOf(orderObj.getWaterNum())))
                  {
                      String deliveryWaterNum = "0";
                      if(collectMap.get(Base64.encodeBase64String(orderObj.getRoomSn().getBytes()))!=null)
                      {
                          deliveryWaterNum = collectMap.get(Base64.encodeBase64String(orderObj.getRoomSn().getBytes())).toString();
                      }
                      errorMessage.append(orderObj.getRoomName()+"应送水"+orderObj.getWaterNum()+",实送水"+deliveryWaterNum+"。");
                      flag = false;
                  }
            }
        }
        resultMap.put("errorMessage",errorMessage.toString());
        resultMap.put("flag",flag);
        return JsonResult.success(resultMap);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public JsonResult updateOutPutBillsAuditStatus(OutPutBillsDTO dto) {
        if(null != dto && null != dto.getId()){
            OutPutBills bean = new OutPutBills();
            BeanUtils.copyProperties(dto,bean);
            bean.setModifyTime(new Date());
            //后续完善
            bean.setModifier("");
            outPutBillsMapper.updateByPrimaryKeySelective(bean);
            //更改当前出货配送单对应的订单状态
            OutPutBillsExample example = new OutPutBillsExample();
            OutPutBillsExample.Criteria criteria =  example.createCriteria();
            criteria.andIdEqualTo(dto.getId());
            /***
             * 修改配送单对应的订单状态
             */
            List<OutPutBills> sysUserList = outPutBillsMapper.selectByExample(example);
            String orderIds =  sysUserList.get(0).getOrderIds();
            StringBuilder orderIdsParams = new StringBuilder();
            orderIdsParams.append("(");
            if(null!=orderIds && !orderIds.equals(""))
            {

                 String[] idArray = orderIds.split(",");
                 for (int i=0;i<idArray.length;i++)
                 {

                     orderIdsParams.append("\"");
                     orderIdsParams.append(idArray[i]);
                     orderIdsParams.append("\"");
                     orderIdsParams.append(",");
                 }
                orderIdsParams.delete(orderIdsParams.length()-1,orderIdsParams.length());
            }
            orderIdsParams.append(")");
            /**批量修改订单状态**/
            Map<String,String> updateStatusParams = new HashMap<>(2);
            updateStatusParams.put("orderId",orderIdsParams.toString());
            updateStatusParams.put("status",String.valueOf(CommonConstants.WATER_ORDER_STATUS_4));
            orderWaterMapper.updateOrderStatusByOrderId(updateStatusParams);
            /**
             * 随着订单的空桶送达到宿舍之后  对学生的空桶送达数进行处理
             */
            orderWaterMapper.updateDepositRecordByOrderId(orderIdsParams.toString());
            /**
             * 对当前配送单的空桶数数据进行处理
             */
            OutPutBillsDTO params_recycle = new OutPutBillsDTO();
            params_recycle.setOrderIds(orderIdsParams.toString());
            List<OrderWater> orderList =  orderWaterMapper.selectWaterNumByOrderId(params_recycle);
            if(orderList!=null && orderList.size()>0)
            {
                for (OrderWater orderWater: orderList)
                {
                    WaterStockExample waterStockExample = new WaterStockExample();
                    WaterStockExample.Criteria criteriaWater =  waterStockExample.createCriteria();
                    criteriaWater.andWaterIdEqualTo(orderWater.getWaterId());
                    List<WaterStock> waterStockList = waterStockMapper.selectByExample(waterStockExample);
                    if(waterStockList.size()>0)
                    {
                        PutInBills updateWaterNumsParams = new PutInBills();
                        updateWaterNumsParams.setWaterId(orderWater.getWaterId());
                        updateWaterNumsParams.setWaterNum(orderWater.getWaterNum());
                        updateWaterNumsParams.setModifier("");
                        updateWaterNumsParams.setModifyTime(new Date());
                        //修改水库存数量
                        waterStockMapper.updateWaterRecycleNumsByWaterId(updateWaterNumsParams);
                    }else{
                        //添加库存记录
                        WaterStock waterStock = new WaterStock();
                        waterStock.setCreater("");
                        waterStock.setCreateTime(new Date());
                        waterStock.setModifier("");
                        waterStock.setModifyTime(new Date());
                        waterStock.setRemark("");
                        waterStock.setStatus(CommonConstants.TABLE_STATUS_1);
                        waterStock.setWaterEmptyNum(orderWater.getWaterNum());
                        waterStock.setWaterId(orderWater.getWaterId());
                        waterStock.setWaterStock(0);
                        waterStockMapper.insert(waterStock);
                    }
                }
            }

            return JsonResult.success();
        }else {
            return JsonResult.fail(ErrorConst.SYSTEM_PARM_ERROR,ErrorConst.SYSTEM_PARM_ERROR_MSG);
        }
    }

    @Override
    public JsonResult<OutPutBillsVO> selectById(Integer id) {
        if(null != id){
            OutPutBills bean = outPutBillsMapper.selectByPrimaryKey(id);
            OutPutBillsVO vo = new OutPutBillsVO();
            if(null != bean){
                BeanUtils.copyProperties(bean,vo);
            }else {
                return JsonResult.fail(ErrorConst.SYSTEM_PARM_ERROR,ErrorConst.SYSTEM_PARM_ERROR_MSG);
            }
            return JsonResult.success(vo);
        }else{
            return JsonResult.fail(ErrorConst.SYSTEM_PARM_ERROR,ErrorConst.SYSTEM_PARM_ERROR_MSG);
        }
    }

    @Override
    public JsonResult<OutPutBillsVO> select(OutPutBillsDTO dto) {
        OutPutBillsExample example = new OutPutBillsExample();
        OutPutBillsExample.Criteria criteria =  example.createCriteria();
        /***
        * 根据具体的业务，查询条件赋值
         */
        List<OutPutBills> sysUserList = outPutBillsMapper.selectByExample(example);
        OutPutBillsVO vo = new OutPutBillsVO();
        if(!sysUserList.isEmpty()){
            BeanUtils.copyProperties(sysUserList.get(0),vo);
        }
        return JsonResult.success(vo);
    }

    @Override
    public JsonResult<PageInfo<OutPutBillsVO>> selectPage(OutPutBillsPageDTO dto) {
        OutPutBillsExample example = new OutPutBillsExample();
        OutPutBillsExample.Criteria criteria =  example.createCriteria();
        /***
        * 根据具体的业务，查询条件赋值
         */
        PageHelper.startPage(dto.getPage(), dto.getLimit());
        List<OutPutBills> beanList = outPutBillsMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo<>(beanList);
        List<OutPutBillsVO> respDTOS = beanList.parallelStream().map((bean) -> {
            OutPutBillsVO vo = new OutPutBillsVO();
            BeanUtils.copyProperties(bean, vo);
            return vo;
        }).collect(Collectors.toList());
        pageInfo.setList(respDTOS);
        return JsonResult.success(pageInfo);
    }

    @Override
    public JsonResult deleteById(Integer id) {
        return JsonResult.success( outPutBillsMapper.deleteByPrimaryKey(id));
    }

    @Override
    public JsonResult delete(OutPutBillsDTO dto) {
        OutPutBillsExample example = new OutPutBillsExample();
        OutPutBillsExample.Criteria criteria =  example.createCriteria();
        /***
        * 根据具体的业务，查询条件赋值
         */
        return JsonResult.success(outPutBillsMapper.deleteByExample(example));
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public JsonResult deleteOrderFromOutPutBillsById(Map<String,String> params) {
        String orderId = params.get("orderId");
        String id = params.get("id");
        OutPutBills updateBillsParams = new OutPutBills();
        updateBillsParams.setId(Integer.parseInt(id));
        OutPutBills bills = outPutBillsMapper.selectByPrimaryKey(Integer.parseInt(id));
        String orderIds = bills.getOrderIds();

        if(orderIds!=null && !orderIds.equals(""))
        {


            if(orderIds.split(",").length == 1)
            {
                orderIds="";
            }else
            if(orderIds.indexOf(","+orderId+",")>0)
            {
                orderIds=  orderIds.replaceAll(","+orderId+",",",");
            }else
            if(orderIds.indexOf(orderId+",") == 0 )
            {
                orderIds= orderIds.substring(orderId.length()+1,orderIds.length());

            }  else
            if(orderIds.indexOf(","+orderId)>0 && (orderIds.indexOf(","+orderId)+orderId.length()+1) == orderIds.length())
            {
                orderIds= orderIds.substring(0,orderIds.length()-orderId.length()-1);
            }


            //获取移除的订单水数量
            String orderIdParams = "(\""+orderId+"\")";
            OutPutBillsDTO billParams = new OutPutBillsDTO();
            billParams.setOrderIds(orderIdParams);
            Map<String,Object> resultMap = orderWaterMapper.selectCountWaterNumsByOrderId(billParams);

            //更新出库单的送水数量/回收桶数量/订单数量
            updateBillsParams.setOrderIds(orderIds);
            updateBillsParams.setWaterNums(Integer.parseInt(resultMap.get("waterNumSum").toString()));
            updateBillsParams.setRecycleBucketSum(Integer.parseInt(resultMap.get("recycleNumSum").toString()));
            updateBillsParams.setOrderNums(1);
            outPutBillsMapper.updateOutBillsWaterNum(updateBillsParams);

            //更新从从出库单移除的订单状态
            OrderWater oWater = new OrderWater();
            oWater.setId(Integer.parseInt(orderId));
            oWater.setStatus(CommonConstants.WATER_ORDER_STATUS_2);
            orderWaterMapper.updateByPrimaryKeySelective(oWater);
        }else
            {
                return JsonResult.fail(ErrorConst.SYSTEM_PARM_ERROR,ErrorConst.SYSTEM_PARM_ERROR_MSG);
            }


        return JsonResult.success();
    }

    @Override
    public JsonResult getRecycleBucketSum(Integer orderId) {
        OutPutBills bills = outPutBillsMapper.selectByPrimaryKey(orderId);

        String orderIds  = StringUtil.toSqlString(bills.getOrderIds());
        int resultNum = 0;
        if(!orderId.equals(""))
        {
            resultNum = outPutBillsMapper.selectRecycleBucketSum(orderIds);
        }
        return JsonResult.success(resultNum);
    }
}